using System;
using System.Threading;
using demo.Tool;
using Newtonsoft.Json;

namespace demo
{
    /// <summary>
    /// 定时任务数据处理器
    /// 负责处理定时任务获取的患者访问数据，包括数据写入和历史数据清理
    /// </summary>
    public class TimerTaskDataProcessor
    {
        private static readonly object lockObject = new object();
        private static Timer cleanupTimer;
        private static bool isInitialized = false;

        /// <summary>
        /// 初始化定时任务数据处理器
        /// </summary>
        public static void Initialize()
        {
            lock (lockObject)
            {
                if (!isInitialized)
                {
                    // 设置每隔一个小时清理历史数据
                    cleanupTimer = new Timer(DailyCleanupCallback, null, TimeSpan.Zero, TimeSpan.FromHours(1));
                    isInitialized = true;
                    
                    Console.WriteLine("定时任务数据处理器已初始化，每隔1小时清理一次历史数据");
                }
            }
        }

        /// <summary>
        /// 处理定时任务获取的患者访问数据
        /// </summary>
        /// <param name="jsonData">从API获取的JSON数据</param>
        /// <returns>处理结果</returns>
        public static bool ProcessPatientData(string jsonData)
        {
            try
            {
                if (string.IsNullOrEmpty(jsonData))
                {
                    Console.WriteLine("错误：输入数据为空");
                    return false;
                }

                // 解析JSON数据
                var data = JsonConvert.DeserializeObject<dynamic>(jsonData);
                if (data?.data?.outP_VISIT_ID == null)
                {
                    Console.WriteLine("错误：数据格式不正确，缺少outP_VISIT_ID字段");
                    return false;
                }

                string outpVisitId = data.data.outP_VISIT_ID.ToString();
                
                // 检查数据是否已存在（去重）
                if (LocalDbHelper.IsPatientVisitIdExists(outpVisitId))
                {
                    Console.WriteLine($"数据已存在，outP_VISIT_ID: {outpVisitId}，跳过保存");
                    return false;
                }

                // 保存数据到本地数据库
                bool saveResult = LocalDbHelper.SavePatientVisitData(jsonData);
                if (saveResult)
                {
                    Console.WriteLine($"患者访问数据保存成功，outP_VISIT_ID: {outpVisitId}");
                    return true;
                }
                else
                {
                    Console.WriteLine($"患者访问数据保存失败，outP_VISIT_ID: {outpVisitId}");
                    return false;
                }
            }
            catch (JsonException ex)
            {
                Console.WriteLine($"JSON解析错误: {ex.Message}");
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理患者数据时发生错误: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 批量处理患者访问数据
        /// </summary>
        /// <param name="jsonDataArray">JSON数据数组</param>
        /// <returns>成功处理的数据条数</returns>
        public static int ProcessBatchPatientData(string[] jsonDataArray)
        {
            if (jsonDataArray == null || jsonDataArray.Length == 0)
            {
                Console.WriteLine("错误：批量数据为空");
                return 0;
            }

            int successCount = 0;
            int totalCount = jsonDataArray.Length;

            Console.WriteLine($"开始批量处理患者数据，总数: {totalCount}");

            for (int i = 0; i < totalCount; i++)
            {
                try
                {
                    if (ProcessPatientData(jsonDataArray[i]))
                    {
                        successCount++;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"处理第 {i + 1} 条数据时发生错误: {ex.Message}");
                }
            }

            Console.WriteLine($"批量处理完成，成功: {successCount}/{totalCount}");
            return successCount;
        }

        /// <summary>
        /// 手动清理历史数据
        /// </summary>
        /// <returns>清理的记录数</returns>
        public static int CleanHistoryData()
        {
            try
            {
                Console.WriteLine("开始清理历史数据...");
                int cleanedCount = LocalDbHelper.CleanNonTodayPatientData();
                
                if (cleanedCount > 0)
                {
                    Console.WriteLine($"历史数据清理完成，清理了 {cleanedCount} 条记录");
                }
                else
                {
                    Console.WriteLine("没有需要清理的历史数据");
                }
                
                return cleanedCount;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"清理历史数据时发生错误: {ex.Message}");
                return 0;
            }
        }

        /// <summary>
        /// 获取当日数据统计信息
        /// </summary>
        /// <returns>统计信息字符串</returns>
        public static string GetTodayDataSummary()
        {
            try
            {
                var stats = LocalDbHelper.GetTodayPatientStatistics();
                var todayData = LocalDbHelper.GetTodayPatientVisitData();
                
                string summary = $"当日数据统计 ({DateTime.Now:yyyy-MM-dd}):\n";
                summary += $"总患者数: {stats["TotalCount"]}\n";
                summary += $"已读患者: {stats["ReadCount"]}\n";
                summary += $"未读患者: {stats["UnreadCount"]}\n";
                summary += $"有检验项目: {stats["WithLisCount"]}\n";
                summary += $"有检查项目: {stats["WithExamCount"]}";
                
                return summary;
            }
            catch (Exception ex)
            {
                return $"获取统计信息失败: {ex.Message}";
            }
        }

        /// <summary>
        /// 检查数据是否已存在
        /// </summary>
        /// <param name="outpVisitId">患者访问ID</param>
        /// <returns>是否存在</returns>
        public static bool IsDataExists(string outpVisitId)
        {
            try
            {
                return LocalDbHelper.IsPatientVisitIdExists(outpVisitId);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"检查数据存在性时发生错误: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 获取当日所有患者数据
        /// </summary>
        /// <returns>患者数据列表</returns>
        public static System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>> GetTodayAllData()
        {
            try
            {
                return LocalDbHelper.GetTodayPatientVisitData();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取当日数据时发生错误: {ex.Message}");
                return new System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>>();
            }
        }

        /// <summary>
        /// 定时清理回调函数
        /// </summary>
        /// <param name="state">状态对象</param>
        private static void DailyCleanupCallback(object state)
        {
            try
            {
                Console.WriteLine($"执行定时清理任务 - {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                int cleanedCount = CleanHistoryData();
                Console.WriteLine($"定时清理任务完成，清理了 {cleanedCount} 条历史记录");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"定时清理任务执行失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 停止定时任务
        /// </summary>
        public static void Stop()
        {
            lock (lockObject)
            {
                if (cleanupTimer != null)
                {
                    cleanupTimer.Dispose();
                    cleanupTimer = null;
                    isInitialized = false;
                    Console.WriteLine("定时任务数据处理器已停止");
                }
            }
        }

        /// <summary>
        /// 析构函数，确保资源释放
        /// </summary>
        ~TimerTaskDataProcessor()
        {
            Stop();
        }
    }
}